package com.example.controller;

import com.example.template.SysRabbitMQTemplate;
import com.example.utils.IdUtils;
import com.rabbitmq.client.AMQP;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;

import javax.annotation.Resource;
import java.nio.charset.StandardCharsets;

@RestController
public class SysRabbitMQController {

    Logger logger = LoggerFactory.getLogger(getClass());

    @Resource
    private SysRabbitMQTemplate sysRabbitMQTemplate;

    /****
     * 发送直连交换机的消息
     * @param exchange
     * @param routingKey
     * @param message
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "sendDirectMQMessage")
    public String sendDirectMQMessage(@RequestParam(defaultValue = "sitc.direct.exchange") String exchange, @RequestParam(defaultValue = "sitc.user.add") String routingKey, String message) throws Exception {
        String uuid = IdUtils.getId();
        if (StringUtils.isEmpty(message)) {
            message = uuid;
        }
        AMQP.BasicProperties properties = new AMQP.BasicProperties.Builder().expiration("10000").build();
        this.sysRabbitMQTemplate.publish(exchange, routingKey, properties, message.getBytes(StandardCharsets.UTF_8));
        return uuid;
    }

    /****
     * 发送广播交换机的消息
     * @param exchange
     * @param routingKey
     * @param message
     * @return
     * @throws Exception
     */
    @RequestMapping(value = "sendFanoutMQMessage")
    public String sendFanoutMQMessage(@RequestParam(defaultValue = "sitc.fanout.exchange") String exchange, @RequestParam(defaultValue = "sitc.fanout.user.queues_") String routingKey, String message) throws Exception {
        String uuid = IdUtils.getId();
        if (StringUtils.isEmpty(message)) {
            message = uuid;
        }
        this.sysRabbitMQTemplate.publish(exchange, routingKey, null, message.getBytes(StandardCharsets.UTF_8));
        return uuid;
    }
}
